var 
    appconfig = require('./appconfig'),
    fs = require('fs'),
    uuid = require('uuid'),
    path = require('path'),
    extend = require('util')._extend,
    us = require('underscore'),
    quploader = require('./quploader'),
    Q = require('q');

   

var _cfg = appconfig.getCfg();
var options = {
    tmpDir:  _cfg.file_upload.tmp_dir,
    uploadDir: _cfg.file_upload.upload_dir,
    uploadUrl:  _cfg.file_upload.upload_url,
    maxPostSize: 11000000, // 11 GB
    minFileSize:  1,
    maxFileSize:  10000000, // 10 GB
    acceptFileTypes:  /\.md/i,
    inlineFileTypes:  /\.(gif|jpe?g|png)/i,
    imageTypes:  /\.(gif|jpe?g|png)/i,
    copyImgAsThumb : false, // required
    imageVersions :{
        maxWidth : 200,
        maxHeight : 200
    },
    accessControl: {
        allowOrigin: '*',
        allowMethods: 'OPTIONS, HEAD, GET, POST, PUT, DELETE',
        allowHeaders: 'Content-Type, Content-Range, Content-Disposition'
    },
    storage : {
        type : 'local'
    }
};

function getDefaultOpts (){
    return extend({},options);
}

var bfu = require('blueimp-file-upload-expressjs');

function upload (req ,resp, fileType) {
    var s = '\.md';
    if(!!fileType){
        if(us.isString(fileType)){
            s = '\.'+fileType;
        }else if(us.isArray(fileType)){
            s = '\.(' + fileType.join('|') + ')';
        }
    }
    var _e = new RegExp(s,'i');
    var opts = extend(getDefaultOpts(), {acceptFileTypes:_e});
    var uploader = bfu(opts);
    var deferred = Q.defer();
    uploader.post(req, resp, function (obj) {
        var _f = obj.files[0];
        if(!!_f.error){
            deferred.reject(_f.error);
        }else{
            var realPath = options.uploadDir + '/' + obj.files[0].name;
            var newName = uuid.v1()  + path.extname(obj.files[0].name);
            var newPath = 
                options.uploadDir + '/' + newName;
            fs.renameSync(realPath, newPath);
            deferred.resolve(newName);            
        }

    });
    return deferred.promise;
}

exports.uploadQiniu = function (req ,resp, fileType){
    upload(req, resp, fileType)
    .then(
    function (name){
        return quploader.upload(options.uploadDir + '/' + name, name);
    },
    function (error){
        console.log(error);
        return error;
    })
    .then(function (r){
        console.log(r);
    },function (err){
        console.log(err);
    });
};

exports.upload = upload;